package com.spzx.payment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.RemoteOrderInfoService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.mapper.PaymentInfoMapper;
import com.spzx.payment.service.IPaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.management.ThreadDumpEndpointAutoConfiguration;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 付款信息Service业务层处理
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements IPaymentInfoService {
    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private RemoteOrderInfoService remoteOrderInfoService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private ThreadDumpEndpointAutoConfiguration threadDumpEndpointAutoConfiguration;


    @Override
    public PaymentInfo savePayment(String orderNo) {

        Long userId = SecurityContextHolder.getUserId();


        //1.去重处理 ： 查询数据库，存在则不用再次保存。不存在则保存
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        if(paymentInfo==null){
            //2.根据订单号查询订单详情
            R<OrderInfo> orderInfoR = remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER);
            if(R.FAIL == orderInfoR.getCode()){
                throw new ServiceException(orderInfoR.getMsg());
            }
            OrderInfo orderInfo = orderInfoR.getData();

            //3.1 组装PaymentInfo信息，
            paymentInfo = new PaymentInfo();
            paymentInfo.setUserId(userId);
            paymentInfo.setOrderNo(orderNo);
            paymentInfo.setPayType(2); //1 微信     2 支付宝
            paymentInfo.setAmount(orderInfo.getTotalAmount()); //实付金额

            List<OrderItem> orderItemList = orderInfo.getOrderItemList();
            StringBuilder builder = new StringBuilder();
            for (OrderItem orderItem : orderItemList) {
                builder.append(orderItem.getSkuName()+";");
            }
            paymentInfo.setContent(builder.toString());
            paymentInfo.setPaymentStatus("0");

            //3.2 保存信息
            paymentInfoMapper.insert(paymentInfo);
        }

        //4.返回PaymentInfo信息
        return paymentInfo;
    }

    @Override
    public void updatePaymentStatus(Map<String, String> paramMap, int paytype) {
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, paramMap.get("out_trade_no")));
        if ("1".equals(paymentInfo.getPaymentStatus())) { //去重处理
            return;
        }

        //更新支付信息
        paymentInfo.setPayType(paytype);
        paymentInfo.setPaymentStatus("1");
        paymentInfo.setTradeNo(paramMap.get("trade_no")); //支付宝和用户之间扣款产生交易流水号
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSON.toJSONString(paramMap));
        paymentInfoMapper.updateById(paymentInfo);

        //基于MQ通知订单系统，修改订单状态
        rabbitService.sendMessage(MqConst.EXCHANGE_PAYMENT_PAY, MqConst.ROUTING_PAYMENT_PAY, paymentInfo.getOrderNo());
    }
}